package ll.com.pro;


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;

// 主界面
public class MainFrame extends JFrame {
    //四行四列的 图片
    private final int[][] imageDate =
            {
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,0}
            };
    private final int[][] winDate =
            {
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,0}
            };
    private static final String IMAGE_PATH = "src/main/resources/image/" ;

    private int Row;
    private int Col;
    private int count;
    private int minStep;
    public MainFrame(){
        //初始化界面
        initFrame();
        //随机打乱数组顺序
        initRandomArray();
        //初始化图片界面
        initImage();
        //初始化系统菜单
        initMenu();
        //给当前窗口绑定上下左右事件
        initKeyPressEvent();
        //给当前窗口绑定上下左右事件
        initKeyMousePress();
        //显示界面
        this.setVisible(true);
    }

    private int scoreReader() {
        try(
                BufferedReader sc = new BufferedReader(new FileReader("./src/historyScore.txt"))
                )
        {
            return Integer.parseInt(sc.readLine());
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    // ... existing code ...
    private void initKeyMousePress() {
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
//                label.setBounds(20+j * 100, 50+i * 100, 100, 100);
                // 获取点击位置
                int x = e.getX();
                int y = e.getY();

                // 计算点击的是哪个方块 (每个方块100x100像素，起始位置是(20, 50))
                int col = (x - 20) / 100;
                int row = (y - 100) / 100;

                // 检查点击位置是否在有效范围内
                if (col >= 0 && col < 4 && row >= 0 && row < 4) {
                    // 判断点击的方块是否与空格子相邻
                    // 上方相邻
                    if (row == Row - 1 && col == Col) {
                        switchAndMove(Direction.Down);
                    }
                    // 下方相邻
                    else if (row == Row + 1 && col == Col) {
                        switchAndMove(Direction.Up);
                    }
                    // 左侧相邻
                    else if (row == Row && col == Col - 1) {
                        switchAndMove(Direction.Right);
                    }
                    // 右侧相邻
                    else if (row == Row && col == Col + 1) {
                        switchAndMove(Direction.Left);
                    }
                }
            }
        });
    }


    private void initKeyPressEvent() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                switch (keyCode) {
                    case KeyEvent.VK_UP:
                        switchAndMove(Direction.Up);
                        break;
                    case KeyEvent.VK_DOWN:
                        switchAndMove(Direction.Down);
                        break;
                    case KeyEvent.VK_LEFT:
                        switchAndMove(Direction.Left);
                        break;
                    case KeyEvent.VK_RIGHT:
                        switchAndMove(Direction.Right);
                        break;
                }
            }
        });
    }
    private void switchAndMove(Direction direction) {
        switch(direction){
            case Up:
                // 上交换的条件：不能是最后一行
                if (Row < imageDate.length-1){
                    int temp = imageDate[Row][Col];
                    imageDate[Row][Col] = imageDate[Row+1][Col];
                    imageDate[Row+1][Col] = temp;
                    Row++;
                    count++;
                }
                break;
            case Down:
                if (Row > 0){
                    int temp = imageDate[Row][Col];
                    imageDate[Row][Col] = imageDate[Row-1][Col];
                    imageDate[Row-1][Col] = temp;
                    Row--;
                    count++;
                }
                break;
            case Left:
                if (Col < imageDate.length-1){
                    int temp = imageDate[Row][Col];
                    imageDate[Row][Col] = imageDate[Row][Col+1];
                    imageDate[Row][Col+1] = temp;
                    Col++;
                    count++;
                }
                break;
            case Right:
                if(Col > 0){
                    int temp = imageDate[Row][Col];
                    imageDate[Row][Col] = imageDate[Row][Col-1];
                    imageDate[Row][Col-1] = temp;
                    Col--;
                    count++;
                }
                break;
        }
        //重新刷新图片
        initImage();
    }

    private void initRandomArray() {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++){
                int a = (int)(Math.random() * imageDate.length);
                switch (a){
                    case 0:
                        // 上交换的条件：不能是最后一行
                        if (Row < imageDate.length-1){
                            int temp = imageDate[Row][Col];
                            imageDate[Row][Col] = imageDate[Row+1][Col];
                            imageDate[Row+1][Col] = temp;
                            Row++;
                        }
                        break;
                    case 1:
                        if (Row > 0){
                            int temp = imageDate[Row][Col];
                            imageDate[Row][Col] = imageDate[Row-1][Col];
                            imageDate[Row-1][Col] = temp;
                            Row--;
                        }
                        break;
                    case 2:
                        if (Col < imageDate.length-1){
                            int temp = imageDate[Row][Col];
                            imageDate[Row][Col] = imageDate[Row][Col+1];
                            imageDate[Row][Col+1] = temp;
                            Col++;
                        }
                        break;
                    case 3:
                        if(Col > 0){
                            int temp = imageDate[Row][Col];
                            imageDate[Row][Col] = imageDate[Row][Col-1];
                            imageDate[Row][Col-1] = temp;
                            Col--;
                        }
                        break;
                }
            }
        }
        OUT:
        for (int i = 0; i < imageDate.length; i++) {
            for (int j = 0; j < imageDate[i].length; j++){
                if (imageDate[i][j] == 0){
                    Row = i;
                    Col = j;
                    break OUT;
                }
            }
        }
    }

    private void initMenu() {
        //创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        //创建菜单
        JMenu menu = new JMenu("系统");
        JMenuItem exitJi = new JMenuItem("退出");
        menu.add(exitJi);
        exitJi.addActionListener(e -> {
            dispose();
        });
        JMenuItem restartJi = new JMenuItem("重新开始");
        menu.add(restartJi);
        restartJi.addActionListener(e -> {
            //重新开始
            initRandomArray();
            count = 0;
            initImage();
        });
        menuBar.add(menu);
        this.setJMenuBar(menuBar);
    }

    private void initImage() {
        //先清空窗口上的全部图层
        this.getContentPane().removeAll();

        minStep=scoreReader();
        //展示文字组件
        JLabel context1 = new JLabel("当前移动"+count+"步");
        context1.setBounds(0, 0, 200, 20);
        context1.setForeground(Color.black);
        context1.setFont(new Font("楷体", Font.BOLD, 15));
        this.add(context1);

        if (minStep!=0){
            JLabel context2 = new JLabel("历史胜利最少步数为"+minStep+"步");
            context2.setBounds(250, 0, 200, 20);
            context2.setForeground(Color.black);
            context2.setFont(new Font("楷体", Font.BOLD, 15));
            this.add(context2);
        }else {
            JLabel context2 = new JLabel("当前没有历史数据");
            context2.setBounds(265, 0, 200, 20);
            context2.setForeground(Color.black);
            context2.setFont(new Font("楷体", Font.BOLD, 15));
            this.add(context2);
        }

        //判断是否赢了
        if(isWin()){
            JLabel label = new JLabel(new ImageIcon(IMAGE_PATH + "victory.png"));
            label.setBounds(90, 220, 250, 50);
            this.add(label);
            int fileMin = scoreReader();
            if (count < fileMin || fileMin == 0){
                scoreWriter(count);
            }
        }
        for (int i = 0; i < imageDate.length; i++){
              for (int j = 0; j < imageDate[i].length; j++){
                  String imageName = imageDate[i][j] + ".png";
                  JLabel label = new JLabel();
                  label.setIcon(new ImageIcon(IMAGE_PATH + imageName));
                  label.setBounds(20+j * 100, 50+i * 100, 100, 100);
                  this.add(label);
              }
        }
        JLabel background = new JLabel(new ImageIcon(IMAGE_PATH + "background.png"));
        background.setBounds(0, 0, 430, 500);
        this.add(background);

        //刷新界面
        this.repaint();
    }

    private void scoreWriter(int count) {
        try(
                BufferedWriter fw = new BufferedWriter( new FileWriter("./src/historyScore.txt"));
                )
        {
            fw.write(count+"");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean isWin() {
        for (int i = 0; i < imageDate.length; i++){
            for (int j = 0; j < imageDate[i].length; j++){
                if (imageDate[i][j] != winDate[i][j]){
                    return false;
                }
            }
        }
        return true;
    }
    private void initFrame(){
        this.setTitle("石头迷阵 v 1.0");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(450, 550);
        this.setLayout(null);
        this.setLocationRelativeTo(null);
    }
}
